/*
 * Copyright (c) 2009.
 */

package kz.home.gui;

import kz.home.db.DBUtils;
import kz.home.http.Http;
import kz.home.parser.JSONParser;
import kz.home.parser.Parser;
import kz.home.utils.Utils;

import javax.microedition.lcdui.*;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStore;
import java.util.Vector;
import java.util.Hashtable;

/**
 * User: danik
 * Date: 05.08.2009
 * Time: 0:07:14
 */
public class MainForm extends BaseForm{
    protected Command cmdSelect;
    protected Command cmdUpdate;
    protected String url="http://kino.one.kz";
    protected String req_url = url + "/kino.php?ajax=true";

    protected Vector schedular;

    public MainForm(BaseForm mainScreen, Display display, Hashtable table) {
        super("", mainScreen, display, table);
        initMainScreen();
    }

    protected void initCommand() {
        cmdUpdate = new Command("Обновить", Command.BACK, 1);
        cmdSelect = new Command("Выбрать", Command.BACK, 2);
    }

    protected void initMainScreen() {
        deleteAll();

        schedular = DBUtils.getFromDB(DBUtils.EVENTS);

        addCommand(cmdUpdate);

        if(schedular.size() == 0) {
            removeCommand(cmdSelect);
            setTitle("Расписание отсутствует");
        } else {
            setTitle("Выберите день");
            addCommand(cmdSelect);
        }

        for (int i = 0; i < schedular.size(); i++) {
            if (schedular.elementAt(i) instanceof Vector) {
                Vector innerVector = (Vector) schedular.elementAt(i);
                if (innerVector.size() > 3) append("" + innerVector.elementAt(3), null);
            }
        }
    }

    public void commandAction(Command command, Displayable displayable) {
        super.commandAction(command, displayable);

        if (command == cmdSelect) {
            if (schedular.size() >= getSelectedIndex()) {
                Vector daySchedular = (Vector) schedular.elementAt(getSelectedIndex());
                setValue("" + daySchedular.elementAt(0));

                CitiesForm citiesForm = new CitiesForm(this, display,request, daySchedular);
                display.setCurrent(citiesForm);
            }
        }

        if (command == cmdUpdate) update();
    }

    protected void update() {
        deleteAll();
        setTitle("Обновление расписания...");
        removeCommand(cmdUpdate);
        removeCommand(cmdSelect);
        append("Удаление старого расписания...", null);
        deletedDB();
        append("Старое расписание удалено.", null);

        new Thread() {
            public void run() {
                try {
                    append("Отправлен запрос...", null);
                    String text = Http.getInstance().requestMainData(url);
                    append("Данные получены.", null);
                    // парсим данные
                    append("Фильтрация данных...", null);
                    Parser parser = new Parser();
                    parser.add(text);
                    Vector vector = parser.parse();
                    append("Данные отфильтрованы.", null);

                    append("Парсинг и сохранение данных...", null);
                    // парсим json данные и сразу сохраняем
                    JSONParser jsonParser = new JSONParser();
                    jsonParser.add(vector);
                    append("Данные пропарсены и сохранены.", null);

                    initMainScreen();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    protected void deletedDB() {
        try {
            RecordStore.deleteRecordStore(DBUtils.MOVIES);
            RecordStore.deleteRecordStore(DBUtils.CINEMAS);
            RecordStore.deleteRecordStore(DBUtils.CITIES);
            RecordStore.deleteRecordStore(DBUtils.EVENTS);
            RecordStore.deleteRecordStore(DBUtils.TIMES);
            RecordStore.deleteRecordStore(DBUtils.ROOMS);
        } catch (RecordStoreException e) {
            Utils.print("error delete db [" + e.getMessage() + "]");
        }
    }

    protected String getParam() {
        return "date";
    }
}
